package znet

import (
	"errors"
	"sync"
	"zinxLearn/pkg/zinx/ziface"
)

type ZConnManager struct {
	connes map[uint32]ziface.IConnection
	mu     sync.RWMutex
}

func NewConnManager() *ZConnManager {
	return &ZConnManager{connes: make(map[uint32]ziface.IConnection), mu: sync.RWMutex{}}
}
func (c *ZConnManager) Add(conn ziface.IConnection) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.connes[conn.GetConnID()] = conn //将conn连接添加到ConnManager中
}
func (c *ZConnManager) Remove(conn ziface.IConnection) {
	c.mu.Lock()
	defer c.mu.Unlock()
	delete(c.connes, conn.GetConnID())
}
func (c *ZConnManager) Get(connID uint32) (ziface.IConnection, error) {
	c.mu.RLock()
	defer c.mu.RUnlock()
	if conn, ok := c.connes[connID]; ok {
		return conn, nil
	} else {
		return nil, errors.New("connection not found")
	}
}
func (c *ZConnManager) Len() int {
	return len(c.connes)
}
func (c *ZConnManager) ClearConn() {
	//保护共享资源Map 加写锁
	c.mu.Lock()
	defer c.mu.Unlock()
	for _, conn := range c.connes {
		conn.Stop()
	}
	c.connes = make(map[uint32]ziface.IConnection)
}
